<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta charset="utf-8">
    <title>College Football</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- STYLES 
    <link href="../../assets/css/bootstrap.css" rel="stylesheet">
    <link href="../../assets/css/bootstrap-responsive.css" rel="stylesheet">  
    -->
    <link href="../../assets/css/datepicker.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

    <!-- LOCAL STYLES -->
    <style type="text/css">
        body {
          padding-top: 60px;
          padding-bottom: 40px;
        }

        #alert-container {
            visibility: hidden;
        }
       .red{
          color: red;
          border-color: red;
        }
       .green{
          color: green;
          border-color: green;
        }
       .bold{
          font-weight: bold
        }

        .btnfixedmed{
          width: 150px; 
        }
        .text-right
        {
            text-align: right !important;
        }

        .text-center
        {
            text-align: center !important;
        }

        .text-left
        {
            text-align: left !important;
        }

        th.first {
            background-color: #e8edff;
            border-left: 0px solid #dddddd;
        }

        th {
            background-color: #e8edff;
        }

        .tiny {
          float: left;
          width: 5px;
        }

    </style>

    <!-- Fav and touch icons -->
    <link rel="shortcut icon" href="../../assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../../assets/ico/apple-touch-icon-57-precomposed.png">
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- JS -->
    <script src="../../assets/js/jquery-1.8.3.js"></script>
    <script src="../../assets/js/jquery.cookie.js"></script>
    <script src="../../assets/js/handlebars-1.0.rc.1.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../assets/js/knockout-latest.debug.js"></script>
    <script src="../../assets/js/sammy.js"></script>
    <script src="../../assets/js/datepicker.js"></script>
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<!--
/**
                              TEMPLATES
 **************************************************************************************************************************************************************************
 ******************************************************************************************************************************************************************************/
-->

    <!--
    /*************************
     * HANDLES BARS TEMPLATES
     *
     *************************
    -->
    <!-- TOP NAVIGATION - START -->
    <script id="top-navigation" type="text/x-handlebars-template">
          <div class="navbar-inner">
            <div class="container">
              <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </a>
              <a class="brand" href="#/home">Conlin Football Pool</a>
              <div class="nav-collapse collapse">
                {{#unless disablenav}}
                  <ul class="nav">
                      {{#if home}}
                        <li class="active">
                      {{else}}
                        <li>
                      {{/if}}
                            <a href="#/home"><i class="icon-star"></i>&nbsp;Leaderboard</a>
                         </li>
                      {{#if isadmin}}  
                        {{#if admin}}
                          <li class="active">
                        {{else}}  
                          <li>
                        {{/if}}
                            <a href="#/weeks"><i class="icon-wrench"></i>&nbsp;Admin</a>
                         </li>
                      {{else}}
                        {{#if makeYourPicks}}
                          <li class="active">
                        {{else}}  
                          <li>
                        {{/if}}
                            <a href="#/playerweeks"><i class="icon-list-alt"></i>&nbsp;Weekly Picks</a>
                          </li>                         
                      {{/if}}
                        <li>
                         <a href="#/signout"><i class="icon-share"></i>&nbsp;Sign out</a>  
                        </li>                        
                  </ul>
                {{/unless}}
              </div>
            </div>
          </div>
    </script>
    <!-- TOP NAVIGATION - END -->

    <!-- SUB NAVIGATION - START --> 
    <script id="sub-navigation" type="text/x-handlebars-template">
        {{#unless disablesubnav}}
        <ul class="nav nav-tabs">
              {{#if weeks}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToWeeksList"><i class="icon-calendar"></i>&nbsp;Weeks</a>
                </li>
              {{#if users}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToUsersList"><i class="icon-user"></i>&nbsp;Users</a>
                </li>   
              {{#if controls}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}    
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToControls"><i class="icon-wrench"></i>&nbsp;Controls</a>
                </li>                                               
        </ul>
        {{/unless}}
        <h3> {{title}}</h3>
    </script>

    <!-- SUB NAVIGATION - END -->

    <!-- ADMIN LOGIN START-->
    <script id="login" type="text/x-handlebars-template">
      <div id="myCarousel" class="carousel slide">
        <div class="carousel-inner">
          <div class="item active">
            <img src="/assets/img/gt_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Who
                </p>
              </div>
            </div>
          </div>
          <div class="item">
            <img src="/assets/img/gator_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Will
                </p>
              </div>
            </div>
          </div>
          <div class="item">
            <img src="/assets/img/win_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Win it All?
                </p>
              </div>
            </div>
          </div>
        </div>
        <a class="left carousel-control" href="#myCarousel" data-slide="prev">&lsaquo;</a>
        <a class="right carousel-control" href="#myCarousel" data-slide="next">&rsaquo;</a>
      </div>
      </div>
        <div class="container"  onKeyPress="return checkSubmit(event)">
          <div class ="row">
            <div class="span6">
              <form action="#/login-form" method="post"> 
                 <label>Username</label>
                  <input type="text" name="username" id="username" placeholder="username">   
                  <label>Password</label>
                  <input type="password" name="password" id="password" placeholder="password">   
                  <label class="checkbox">
                    <input type="checkbox" name="remember" id="remember">Remember Me
                  </label>
                  <div class="container">
                    <button class="btn btn-small" type="submit">Login</button>
                  </div>
              </form>
            </div>
          </div>
        </div>
    </script> 
    <!-- ADMIN LOGIN END -->

    <!--
      ******************************************************************************************************
      USER Templates
      ******************************************************************************************************
    -->

  <!-- HOME SCREEN -->
    <script id="home" type="text/x-handlebars-template">
        <table class="table table-hover table-striped table-condensed table-bordered">
            <thead>
                <tr>
                    <th>Week</th>
                  <!-- ko foreach: columnnames -->   
                    <th><b data-bind="text: $data"></b></th>
                  <!-- /ko --> 
                </tr>
              </thead>
              <tbody>
                <!-- ko foreach: rows -->  
                  <tr>
                    <td id="weeknumber" data-bind="text: $data[0]"></td>
                    <!-- ko foreach: $parent.columnnames -->
                      <td class="userscore" data-bind="text: $parent[$index()+1]"></td>
                    <!-- /ko -->         
                  </tr>
                <!-- /ko -->
                  <tr class="top">
                    <td class="bold">Average</td>
                    <!-- ko foreach: averages -->
                      <td class="text-left bold" data-bind="text: $data"></td>
                    <!-- /ko --> 
                  </tr>                  
                  <tr>
                    <td class="bold">Total</td>
                    <!-- ko foreach: totals -->
                      <td class="text-left bold" data-bind="text: $data"></td>
                    <!-- /ko --> 
                  </tr>                  
              </tbody>                   
        </table>
    </script>
  <!-- -->

  <!-- SCOREBOARD SCREEN -->
    <script id="scoreboard" type="text/x-handlebars-template">
        <table class="table table-hover table-striped table-condensed table-bordered">
            <thead>
                <tr>
                    <th>Datetime</th>
                    <th>Favorite</th>
                    <th>Underdog</th>
                    <th>Spread</th>
                    <th>Score</th>
                  <!-- ko foreach: columnnames -->   
                    <th><b data-bind="text: $data"></b></th>
                  <!-- /ko --> 
                </tr>
              </thead>
              <tbody>
                <!-- ko foreach: rows -->  
                  <tr>
                    <input id="winner" data-bind="value: $data[0].winner" name="winner" type="hidden"/>
                    <input id="favoredlocation" data-bind="value: $data[0].favoredlocation" name="favoredlocation" type="hidden"/>
                    <input id="completed" data-bind="value: $parent.booleanConversion($data[0].completed)" name="completed" type="hidden"/>
                    <td data-bind="text: $parent.dateTimeField($data[0])"></td>                    
                    <td id="favorite" data-bind="text: $data[0].favorite"></td>
                    <td id="underdog" data-bind="text: $data[0].underdog"></td>
                    <td data-bind="text: $data[0].spread"></td>
                    <td>
                      <span data-bind="text: $data[0].scorefavored"/> - <span id="scoreunderdog" data-bind="text: $data[0].scoreunderdog"/>
                    </td>
                    <!-- ko foreach: $parent.columnnames -->
                      <td class="userpick" data-bind="text: $parent[$index()+1]"></td>
                    <!-- /ko -->         
                  </tr>
                <!-- /ko -->  
                  <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <!-- ko foreach: totals -->
                      <td class="text-left" data-bind="text: $data"></td>
                    <!-- /ko --> 
                  </tr>
              </tbody>                   
        </table>
    </script>
  <!-- -->

    <!-- USER WEEK LIST  - START -->
    <script id="player-weeks-list" type="text/x-handlebars-template">
        <table class="table table-hover table-striped table-condensed table-bordered">
              <thead>
                  <tr>
                    <th>Week</th>
                    <th>Date Range</th>
                    <th>Status</th>
                    <th>&nbsp;</th>
                  </tr>
                </thead>
                <tbody>
                <!-- ko foreach: weeks -->    
                  <tr>
                    <td data-bind="text: weeknumber"></td>
                    <td data-bind="text: daterange"></td>             
                    <td>
                      <!-- ko if: complete -->
                        Complete
                      <!-- /ko -->
                      <!-- ko ifnot: complete  --><!-- ko if: active -->
                        Active
                      <!-- /ko --><!-- /ko -->
                      <!-- ko ifnot: active  --><!-- ko ifnot: complete -->
                        Pending
                      <!-- /ko --><!-- /ko -->                  
                    </td>
                    <td>
                        <!-- ko ifnot: active  --><!-- ko ifnot: complete -->
                          <a href="#" data-bind="click: $root.goToPlayerPicks"class="btn btn-link">Make Picks</a>
                        <!-- /ko --><!-- /ko -->
                        <!-- ko if: active  -->
                          <a href="#" data-bind="click: $root.goToWeekScore"class="btn btn-link">Scoreboard</a>
                        <!-- /ko -->
                        </td>
                  </tr>
                <!-- /ko -->  
                </tbody>
        </table>      
    </script>

    <!-- USER PICK WEEK LIST  - START -->
    <script id="player-picks" type="text/x-handlebars-template">
            <ul class="nav nav-pills">
              <li><a href="#" data-bind="click: $root.goToPlayerPickWeeksList" ><i class="icon-arrow-left"></i>&nbsp;Back to All Weeks</a></li>
            </ul>
            <table class="table table-hover table-condensed">
              <thead>
                  <tr>
                    <th>Date</th>
                    <th>Time</th>
                    <th>Favorite</th>
                    <th>Underdog</th>
                    <th>Spread</th>
                    <th>Pick</th>
                  </tr>
                </thead>
                <tbody data-bind="foreach: games">
                  <tr >
                    <td data-bind="text: $parent.showGameDate(gamedate)"></td>
                    <td data-bind="text: time.label"></td>
                    <td data-bind="text: favorite, style: { fontWeight: favoredlocation == 'HOME' ? 'bold' : 'normal' }"></td>
                    <td data-bind="text: underdog, style: { fontWeight: favoredlocation == 'AWAY' ? 'bold' : 'normal' }"></td>
                    <td data-bind="text: spread"></td>
                    <td>
                        <div class="btn-group btn-block" data-toggle="buttons-radio">  
                          <button id="btn-favorite" type="button" data-toggle="button" data-bind="attr: {name: favorite}" class="btn btnfixedmed"><span data-bind="text: favorite"></span></button>
                          <input data-bind="value: pick" name="pick" type="hidden"/>
                          <button id="btn-underdog" type="button" data-toggle="button" data-bind="attr: {name: underdog}" class="btn btnfixedmed"><span data-bind="text: underdog"></span></button>
                        </div>
                    </td>
                  </tr>
                </tbody>
            </table>
            <div class="container">
              <button data-bind="click: $root.saveWeek" class="btn btn-small btn-primary ">Save Week</button>
              <button data-bind="click: $root.goToPlayerPickWeeksList" class="btn btn-small">Cancel</button>
            </div>              
    </script>

    <!--
      ******************************************************************************************************
      Admin Templates
      ******************************************************************************************************
    -->

    <!-- CONTROLS SCREEN -->
    <script id="controls" type="text/x-handlebars-template">
      <div class="container">
        <div id="buttondiv" class="container">
          <table class="table table-hover table-condensed">
            <thead>
                <tr>
                  <th>Action</th>
                  <th>Description</th>
                </tr>
            </thead>
            <tbody> 
            <tr>
              <td>
                <button data-bind="click: $root.runscore" class="btn btn-small btn-success ">Score Weeks</button>
              </td>
              <td>
                Examine user picks against actual games and reward points if users picked correctly
              </td>
            </tr>            
          </tbody>
        </table>           
        </div>  
      </div>
    </script>
    <!-- -->

    <!-- Admin Users List - START -->
    <script id="users-list" type="text/x-handlebars-template">
      <div class="container">
        <table class="table table-hover table-condensed">
        <thead>
            <tr>
              <th>User Id</th>
              <th>Username</th>
              <th>Role</th>
              <th>Password</th>
              <th>&nbsp;</th>
            </tr>
        </thead>
        <tbody>
          <!-- ko foreach: users -->    
          <tr>
            <td data-bind="text: id"></td>
            <td data-bind="text: username"></td>
            <td data-bind="text: role"></td>
            <td data-bind="text: password"></td>
            <td>
                <a href="#" data-bind="click: $root.goToUser"class="btn btn-link">Edit</a>
                <a href="#" data-bind="click: $root.removeUser"><i class="icon-remove"></i></a>
            </td>
          </tr>
          <!-- /ko -->  
        </tbody>
        </table>
      </div>
      <!-- CONTAINER - Table of Users - END -->
      <!-- BUTTONS - START -->
      <div class="container">
        <button data-bind="click: goToUser" class="btn btn-small btn-success">Add / Create a User</button>
      </div>
      <!-- BUTTONS - END -->
    </script>
    <!-- Admin Users List - END -->

    <!-- User Create / Edit START-->
    <script id="user-edit" type="text/x-handlebars-template">
      <div class="container well">
        <form>
         <fieldset>
          <label>Id</label>
          <input data-bind="value: id" type="text" placeholder="">   
          <label>Username</label>
          <input data-bind="value: username" type="text" placeholder="gtfan#1">
          <label>Role</label>
          <select data-bind="options: $root.availableRoles, value: role, optionsText: 'label', optionsValue: 'value'" size=1></select>
          <label>Password</label>
          <input data-bind="value: password" type="text" placeholder="secret password">      
          </fieldset>
        </form>  
        <div class="container">
          <button data-bind="click: saveUser" class="btn btn-small btn-warning">Save</button>
          <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
        </div>
      </div> 
    </script>
    <!-- User Create / Edit END -->

    <!-- CONTENT - WEEK EDIT  - START -->
    <script id="week-edit" type="text/x-handlebars-template">
        <div class="container well">
        <form>
        <fieldset>
          <div class="clearfix">
          <div class="row">
            <div class="span2">
              <label>Week Number</label>
              <label class="checkbox">
                <input data-bind="checked: published"  type="checkbox">
                Publish this Week
              </label>              
            </div>
            <div class="span2">
              <input data-bind="value: weeknumber" maxlength="2" class="span1" type="text"/>
            </div>
          </div>
          <BR>
          <div class="row">       
            <div class="span2">
              <label>Favorite</label>
            </div>
            <div class="span2">
              <label>Underdog</label>
            </div>
            <div class="span1">
              <label>Spread</label>
            </div>
            <div class="span2">
              <label>Date</label>
            </div>
            <div class="span2">
              <label>Time</label>
            </div>
            <div class="span2">
              <label>Favored Is</label>
            </div>
            <div class="span1">
              &nbsp;
            </div>
          </div>
          <!-- ko foreach: games -->
            <div class="row">           
              <div class="span2">
                <input data-bind="value: favorite"  class="span2 team" type="text" placeholder="Team Name"/>
              </div>
              <div class="span2">
                <input data-bind="value: underdog"  class="span2 team" type="text" placeholder="Team Name"/>
              </div>
              <div class="span1">
                <input data-bind="value: spread" maxlength="4" class="span1" type="text"/>
              </div>
              <div class="span2">
                <input data-bind="value: gamedate" data-datepicker="datepicker" class="span2" id="inputIcon" type="text" placeholder="MM/DD/YYYY" />
              </div>
              <div class="span2">
                <select data-bind="options: $root.availableTimes, value: timestr, optionsText: 'label', optionsValue: 'value'"  class="span2" size=1></select>
              </div>
              <div class="span2"> 
                <div class="btn-group" data-toggle="buttons-radio">  
                  <button id="btn-home" type="button" data-toggle="button" name="HOME" value="" class="btn">Home</button>
                  <input data-bind="value: favoredlocation" name="favoredlocation" type="hidden"/>
                  <button id="btn-away" type="button" data-toggle="button" name="AWAY" value="" class="btn">Away</button>
                  <button id="btn-away" type="button" data-toggle="button" name="NEUTRAL" value="" class="btn">Neutral</button>
                </div>
              </div>
              <div  class="span1">
                <a href="#" data-bind="click: $root.removeGame"><i class="icon-remove"></i></a> 
              </div>
            </div>         
          <!-- /ko -->
            <div class="row">
              <div class="span2">
                Game Count : <span data-bind="text: games().length"></span>
              </div>
            </div>             
        </fieldset>
        </form>
        </div>
        <div class="container">
          <button data-bind="click: addGame" class="btn btn-small btn-success">Create another Game</button>
          <button data-bind="click: saveWeek" class="btn btn-small btn-primary ">Save Week</button>
          <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
        </div>
    </script>

    <!-- WEEK LIST  - START -->
    <script id="weeks-list" type="text/x-handlebars-template">
        <table class="table table-hover table-condensed">
              <thead>
                  <tr>
                    <th>Week</th>
                    <th>Date Range</th>
                    <th>Status</th>
                    <th>&nbsp;</th>
                  </tr>
                </thead>
                <tbody>
                <!-- ko foreach: weeks -->    
                  <tr>
                    <td data-bind="text: weeknumber"></td>
                    <td data-bind="text: daterange"></td>
                    <td>
                      <!-- ko if: published -->
                        Published  
                      <!-- /ko -->
                      <!-- ko if: complete -->
                        Complete
                      <!-- /ko -->
                    </td>
                    <td>
                      <a href="#" data-bind="click: $root.goToWeek" class="btn btn-link">Edit</a>
                      <a href="#" data-bind="click: $root.goToWeekScore"class="btn btn-link">Score</a>
                      <a href="#" data-bind="click: $root.removeWeek"><i class="icon-remove"></i></a>   
                    </td>
                  </tr>
                <!-- /ko -->  
                </tbody>
        </table>
        <div id="buttondiv" class="container">
            <a href="#" data-bind="click: $root.goToWeek" class="btn btn-small btn-success">Add / Create a Week</a>
        </div>
    </script>

    <!-- WEEK SCORE  - START -->
    <script id="week-score" type="text/x-handlebars-template">
      <div class="container well">
      <form>
      <fieldset>
        <div class="clearfix">
        <div class="row">
          <div class="span2">
            <label>Week Number</label>
          </div>
          <div class="span1">
            <span data-bind="text: weeknumber" class="span1 uneditable-input" />
          </div>
        </div>
        <div class="row"> 
          <div class="span2"><label>Score</label></div>      
          <div class="span2"><label>Favorite</label></div>
          <div class="span2"><label>Underdog</label></div>
          <div class="span1"><label>Spread</label></div>
          <div class="span2"><label>Date</label></div>
          <div class="span1"><label>Time</label></div>
          <div class="span2"><label>Favored Is</label></div>
        </div>
        <!-- ko foreach: games -->
          <div class="row datarow"> 
            <div class="span2">
              <input data-bind="value: scorefavored"  class="span1 input" name="sfav" type="text"/>
              <input data-bind="value: scoreunderdog" class="span1 input" name="sund" type="text"/>
              <input data-bind="value: winner" type="hidden" class="winner"/>
            </div>        
            <div class="span2">
              <span data-bind="text: favorite"  class="span2 uneditable-input favorite" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: underdog"  class="span2 uneditable-input underdog" type="text"/>
            </div>
            <div class="span1">
              <span data-bind="text: spread" maxlength="2" class="span1 uneditable-input spread" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: gamedate" class="small uneditable-input" type="text" />
            </div>
            <div class="span1">
              <span data-bind="text: time.label" maxlength="2" class="span1  uneditable-input" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: favoredlocation" maxlength="2" class="span1 uneditable-input" type="text"/>
            </div>
          </div>
        <!-- /ko -->
      </fieldset>
      </form>
      </div> <!-- /container -->
      <div class="container">
        <button data-bind="click: saveGameScores" class="btn btn-small btn-primary ">Save Week</button>
        <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
      </div>
    </script>


   <!-- MESSAGE - START -->
  <script id="message" type="text/x-handlebars-template">
        <div class="alert {{alertclass}} fade in">
              <button type="button" class="close" data-dismiss="alert">&times;</button>
              <p>{{alertmessage}}</p>
        </div>
  </script>

  </head>           
  <body>
      <!-- target divs for templates START -->

      <div id="navigationdiv" class="navbar navbar-inverse navbar-fixed-top"></div>
      <div id="messagediv" class="container"></div>
      <div id="subnavigationdiv" class="container"></div>
      <div id="contentdiv" class="container"></div>
      
      <!-- target divs for templates END -->

<!--
/**
                              MODELS
 **************************************************************************************************************************************************************************
 ******************************************************************************************************************************************************************************/
-->
<script>

  // ******************************************************************************************************************
  // ControlViewModel
  //
  // Admin System Controls screen - for overall system info display and controls for running tests
  //
  //
  function ControlViewModel()
  {
    cflog("ControlViewModel : init : ");
    var self = this;   

    // Model Construction
    // take api results and build model
    self.loadscoreresults = function(data){
      CFBMESSAGE.success("Player Scores Updated");
      cflog("loadScoreResults");
      cflog(data);
    };

    // Model Construction
    // take api results and build model
    self.usercreateresults = function(data){
      CFBMESSAGE.success("Users Created");
      cflog("usercreateresults");
      cflog(data);
    };

    self.createusers = function() {
      cflog("ControlViewModel : createusers ");
      CFBAPI.get('/uc/user/createtestusers', 
          function (result) {self.usercreateresults(result);},
          function (XMLHttpRequest, textStatus, errorThrown) {
              CFBMESSAGE.error("Could not createtestusers");
              cflog(textStatus);
              cflog(errorThrown);
      });
      return true;

    }

    self.runscore = function() {
      cflog("ControlViewModel : runscore ");
      CFBAPI.get('/admin/run/scores', 
          function (result) {self.loadscoreresults(result);},
          function (XMLHttpRequest, textStatus, errorThrown) {
              CFBMESSAGE.error("Could not run scores");
              cflog(textStatus);
              cflog(errorThrown);
      });
      return true;
    };

  }

  // ******************************************************************************************************************
  // Weeks Model 
  //
  // handles list of weeks, results are shown if applicable, edit, delete controls presented
  //
  //
  function WeeksViewModel() 
  {
      cflog("WeeksViewModel : init : ");

      var self = this;   
      self.weeks = ko.observableArray([]);
      
      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      };

      self.removeWeek = function(week) {
        cflog('remove week : ' + week.weeknumber);
        CFBAPI.get('/admin/week/delete/' + week.weeknumber, 
            function (result) {
              CFBMESSAGE.success("Week Removed!");
              self.weeks.remove(week);
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not remove Week");
                cflog(textStatus);
                cflog(errorThrown);
        });
      };

      self.loadWeeks = function() {
        cflog("WeeksViewModel : loadWeeks ");
        CFBAPI.get('/admin/weeks', 
            function (result) {self.loadWeeksFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load list of Weeks");
                cflog(textStatus);
                cflog(errorThrown);
        });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadWeeksFromServer = function(data){
        cflog("loadweeksfromserver");
        cflog(data);
        self.weeks(data);
      };

      self.goToWeek = function(week) { 
          cflog('goToWeek : ' + week.weeknumber);
          var wknum = week.weeknumber;

          if(typeof week.weeknumber == 'undefined')
          {
            wknum = -1;
          }

          location.hash = '/week/' + wknum; 
      };

      self.goToWeekScore = function(week) {
          cflog('goToWeekScore');
          location.hash = '/week/score/' + week.weeknumber; 
      };

      // INIT
      // 

      self.loadWeeks();
  };

  // ******************************************************************************************************************
  // GamesViewModel  - 
  // Add / Edit / Delete Games of the Week
  // For handling list of games of the week
  // Pick matchups, set the spread, home team, time, etc
  //
  
  function Game(favorite, underdog, spread, gamedate, favoredlocation, time) 
  {
        var self = this;
        self.favorite = ko.observable(favorite);
        self.underdog = ko.observable(underdog);  
        self.spread = ko.observable(spread);  
        self.gamedate = ko.observable(gamedate);
        self.favoredlocation = ko.observable(favoredlocation);  
        //self.time = ko.observable(time);  
        self.timestr = ko.observable(time);
  };

  function refreshGamesViewModel()
  {
    var allTeams = ["Cincinnati","Connecticut","Houston","Louisville","Memphis","Rutgers","South Florida","Southern Methodist","Temple","UCF","Boston College","Clemson","Duke","Florida State","Georgia Tech","Maryland","Miami (FL)","North Carolina","North Carolina State","Pittsburgh","Syracuse","Virginia","Virginia Tech","Wake Forest","Baylor","Iowa State","Kansas","Kansas State","Oklahoma","Oklahoma State","TCU","Texas","Texas Tech","West Virginia","Illinois","Indiana","Iowa","Michigan","Michigan State","Minnesota","Nebraska","Northwestern","Ohio State","Penn State","Purdue","Wisconsin","East Carolina","Florida Atlantic","Florida International","Louisiana Tech","Marshall","Middle Tennessee","North Texas","Rice","Southern Miss","Tulane","Tulsa","UAB","UTEP","UTSA","Army","Brigham Young","Idaho","Navy","New Mexico State","Notre Dame","Old Dominion","Akron","Ball State","Bowling Green","Buffalo","Central Michigan","Eastern Michigan","Kent State","Massachusetts","Miami (OH)","Northern Illinois","Ohio","Toledo","Western Michigan","Air Force","Boise State","Colorado State","Fresno State","Hawaii","Nevada","New Mexico","San Diego State","San Jose State","UNLV","Utah State","Wyoming","Arizona","Arizona State","California","Colorado","Oregon","Oregon State","Stanford","UCLA","USC","Utah","Washington","Washington State","Alabama","Arkansas","Auburn","Florida","Georgia","Kentucky","LSU","Mississippi State","Missouri","Ole Miss","South Carolina","Tennessee","Texas A&M","Vanderbilt","Arkansas State","Georgia State","Louisiana-Lafayette","Louisiana-Monroe","South Alabama","Texas State","Troy","Western Kentucky","Big Sky","Cal Poly","Eastern Washington","Idaho State","Montana","Montana State","North Dakota","Northern Arizona","Northern Colorado","Portland State","Sacramento State","Southern Utah","UC Davis","Weber State","Charleston Southern","Coastal Carolina","Gardner-Webb","Liberty","Presbyterian","Virginia Military Institute","Albany","Delaware","James Madison","Maine","New Hampshire","Rhode Island","Richmond","Stony Brook","Towson","Villanova","William & Mary","Abilene Christian","Charlotte","Houston Baptist","Incarnate Word","Monmouth","Brown","Columbia","Cornell","Dartmouth","Harvard","Pennsylvania","Princeton","Yale","Bethune-Cookman","Delaware State","Florida A&M","Hampton","Howard","Morgan State","Norfolk State","North Carolina A&T","North Carolina Central","Savannah State","South Carolina State","Illinois State","Indiana State","Missouri State","North Dakota State","Northern Iowa","South Dakota","South Dakota State","Southern Illinois","Western Illinois","Youngstown State","Bryant University","Central Connecticut State","Duquesne","Robert Morris","Sacred Heart","St. Francis (PA)","Wagner","Austin Peay","Eastern Illinois","Eastern Kentucky","Jacksonville State","Murray State","Southeast Missouri State","Tennessee State","Tennessee Tech","Tennessee-Martin","Bucknell","Colgate","Fordham","Georgetown","Holy Cross","Lafayette","Lehigh","Butler","Campbell","Davidson","Dayton","Drake","Jacksonville","Marist","Mercer","Morehead State","San Diego","Stetson","Valparaiso","Appalachian State","Chattanooga","Citadel","Elon","Furman","Georgia Southern","Samford","Western Carolina","Wofford","Central Arkansas","Lamar","McNeese State","Nicholls State","Northwestern State","Sam Houston State","Southeastern Louisiana","Stephen F. Austin","Alabama A&M","Alabama State","Alcorn State","Arkansas-Pine Bluff","Grambling State","Jackson State","Mississippi Valley State","Prairie View A&M","Southern University","Texas Southern"];
    
    // css consts
    var selectedRadioCSS = 'btn btn-info';
    var notSelectedRadioCSS = 'btn';

    // set up cals for all date fields
    $('[data-datepicker]').datepicker();

     // Radio Button - Hidden Input - Toggle
     // check our toggle buttons and hidden fields are synched up
     var buttons = $('.btn-group').each( function(index, el){
              var hidden = $(el).find('input');
              var match = hidden.siblings('button[name="'+ hidden.val() + '"]').attr('class', selectedRadioCSS);
              var notmatch = match.siblings('button').attr('class', notSelectedRadioCSS);
                });

     $('.team').typeahead({source: allTeams, items:5});

      // TOGGLE RADIO BUTTONS - onClick
      // for home and away
      // will work on all added rows
      $("form").delegate(".btn", "click", function() {
          var clicked = $(this);                //who was clicked
          var hidden = clicked.siblings('input'); 

          if(clicked.attr('name') != hidden.val())
          {
            var sibling = clicked.siblings('button')   //find button that was not clicked
            var currentCSS = clicked.attr('class');     //get clicked existing style/state
            var CSS_1 = $(sibling[0]).attr('class');       //get not clicked existing style/state
            var CSS_2 = $(sibling[1]).attr('class');
            var newCSS = CSS_1;

            if(currentCSS == CSS_1 && currentCSS != CSS_2) {
              newCSS = CSS_2
            }

            if(currentCSS != CSS_1 && currentCSS == CSS_2){
              newCSS = CSS_1
            }

            clicked.attr('class', newCSS);          //flip styles
            $(sibling[0]).attr('class', currentCSS);
            $(sibling[1]).attr('class', currentCSS);

            //update hidden prop and switch values
            hidden.val(clicked.attr('name'));
            hidden.trigger("change");           //let ko know we changed hidden value     
          }
      });
  };

  function GamesViewModel(weeknumber) 
  {
      var self = this;   

      cflog("GamesViewModel : initialized : " + weeknumber);

      // FILTER MODEL ITEMS
      var MODEL_COLS = ["weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "gamedate", "timestr", "time", "label", "value", "scorefavored", "scoreunderdog", "winner", "completed", "published" ];
      
      // CONSTANTS
      //
      self.availableTimes = CONSTANTS.times;

      // OBSERVABLE DATA
      //
      self.weeknumber = ko.observable();
      self.games = ko.observableArray([]);
      self.published = ko.observable();

      /********** Actions / Helpers ***********/

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      //
      // ACTIONS
      //
      self.addGame = function() {
        self.games.push(new Game("","","","","HOME","12:00"));
        refreshGamesViewModel();
      };
     
     // REMOVE
     //
      self.removeGame = function(game) {
       self.games.remove(game)
      };

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 

          if(weeknumber >= 1)
          {
            CFBAPI.get('/admin/week/' + weeknumber, 
              function (result) {self.parseWeekFromServer(result);},
              function (XMLHttpRequest, textStatus, errorThrown) {
                  CFBMESSAGE.error("Could not load Week");
                  cflog(textStatus);
                  cflog(errorThrown);
              });
          }
        return true;
      };

      // Model Constructio
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("parseweekfromserver");
        cflog(data);
        self.games(data.games);
        self.games( self.games().sort(function(l, r) {return l.timeinmillis == r.timeinmillis ? 0 : (l.timeinmillis < r.timeinmillis ? -1 : 1) }));
        self.weeknumber(data.weeknumber);
        self.published(data.published);
        refreshGamesViewModel();  
      };

      // SAVE
      //
      self.saveWeek = function() {
          cflog("GamesViewModel : saveWeek");
          cflog(ko.toJSON(self));
          var jsonData = self.cleanJSON();

          cflog(jsonData);

          CFBAPI.post('/admin/week/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Week Saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save Week");
                cflog(textStatus);
                cflog(errorThrown);
            });
          
        return true;
      };

      // CANCEL
      //
      self.cancel = function() {
          cflog('GamesViewModel : cancel');
          ADMINNAVHELPER.goToWeeksList()
      };

      // INIT 
      //
      self.loadWeek(weeknumber);
  };

  // ******************************************************************************************************************
  // USER View Models
  //

  function UserViewModel(id) 
  {    
    var self = this;
    self.id =  ko.observableArray();
    self.username =  ko.observableArray();
    self.role =  ko.observableArray();
    self.password =  ko.observableArray();
    var MODEL_COLS = ["id", "username", "password", "role", "label", "value"];

    // Valid Roles
    //
    self.availableRoles = [
      { label: "Admin", value:  "ROLE_ADMIN" },
      { label: "Player", value: "ROLE_USER" }
    ]; 

    //return only the json we need from the model
    //
    self.cleanJSON = function()
    {
      self.role = self.role();
      var jsonData = ko.toJSON(self, MODEL_COLS);
      return jsonData;
    }

    // CANCEL
    //
    self.cancel = function() 
    { 
      cflog( "Cancel User Edit Called" );
      ADMINNAVHELPER.goToUsersList();
    };

    // SAVE USER 
    //
    self.saveUser = function () {
      cflog("save user called");
      cflog(self.role());
      var jsonData = self.cleanJSON();
      cflog(jsonData);

      CFBAPI.post('/uc/user/save', jsonData, 
        function (result) { 
          cflog(result);
          CFBMESSAGE.success("User saved!");
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            CFBMESSAGE.error("Failed to save users");
            cflog(textStatus);
            cflog(errorThrown);
        });


      //ADMINNAVHELPER.goToUsersList();
      cflog("save user done");
      return true;
    };

    // LOAD USER
    // TODO : load user from server call
    //
    self.loadUserFromServer = function( data ) 
    {
      cflog( "loadUserFromServer" );
      cflog(data);
      self.id( data.id );
      self.role ( data.role );
      self.password( data.password );
      self.username( data.username );
    }

    self.loadUser = function(id) {
      cflog("UsersViewModel : loadUser : ");
      CFBAPI.get('/uc/user/' + id,  
          function (result) {
              self.loadUserFromServer(result); 
          },
          function (XMLHttpRequest, textStatus, errorThrown) {
              CFBMESSAGE.error("Could not load user");
              cflog(textStatus);
              cflog(errorThrown);
          });
      return true;
    };


    //INIT
    //
    self.loadUser(id);
  };

  // ******************************************************************************************************************
  // USERS LIST View Model
  //
  function UsersViewModel() 
  {
      var self = this;         
      self.users = ko.observableArray([]);

      // Valid Roles
      //
      self.availableRoles = [
        { label: "Admin", value:  "Admin" },
        { label: "Player", value: "Player" }
      ]; 

      self.loadUsers = function() {
        cflog("UsersViewModel : loadUsers : ");
        CFBAPI.get('/uc/users',  
            function (result) {
                self.loadUsersFromServer(result); 
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load users");
                cflog(textStatus);
                cflog(errorThrown);
            });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadUsersFromServer = function(data){
        cflog(data);
        self.users(data);
      };

      // Behaviours
      //    

      // ADD / EDIT USER
      //
      self.goToUser = function(user) { 
          cflog('goToUser');
          location.hash = '/user/' + user.id; 
      };

      // Remove User
      //
      self.removeUser = function(usertoremove) {
        cflog('remove user : ' + usertoremove.id);
        CFBAPI.get('/uc/user/delete/' + usertoremove.id, 
            function (result) {
              CFBMESSAGE.success("User Removed!");
              self.users.remove(usertoremove);
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not remove User");
                cflog(textStatus);
                cflog(errorThrown);
        });
      };


      //INIT
      //
      self.loadUsers();
  };

  // ******************************************************************************************************************
  // PICK WEEK 
  // Model for picking games of the week
  //

  //refreshPickViewModel
  //
  function refreshPickViewModel()
  {
    cflog("refreshPickViewModel : start");
    // css consts
    var selectedRadioCSS = 'btn btn-success btnfixedmed';
    var notSelectedRadioCSS = 'btn btnfixedmed';

     // Radio Button - Hidden Input - Toggle
     // check our toggle buttons and hidden fields are synched up
     var buttons = $('.btn-group').each( function(index, el){
              var hidden = $(el).find('input');
              var match = hidden.siblings('button[name="'+ hidden.val() + '"]').attr('class', selectedRadioCSS);
              var notmatch = match.siblings('button').attr('class', notSelectedRadioCSS);
                });

      // TOGGLE RADIO BUTTONS - onClick
      // for home and away
      // will work on all added rows
      $("table").delegate(".btn", "click", function() {
          var clicked = $(this);                //who was clicked
          var hidden = clicked.siblings('input'); 
          
          if(clicked.attr('name') != hidden.val())
          {
            var sibling = clicked.siblings('button');   //find button that was not clicked
            var currentCSS = clicked.attr('class');     //get clicked existing style/state
            var newCSS = sibling.attr('class');       //get not clicked existing style/state

            clicked.attr('class', selectedRadioCSS);          //clicked gets lite up
            sibling.attr('class', notSelectedRadioCSS);

            //update hidden prop and switch values
            hidden.val(clicked.attr('name'));
            hidden.trigger("change");           //let ko know we changed hidden value     
          }
      });
  };

  function WeekPickViewModel(weeknumber) {

     var self = this;   
     self.games = ko.observableArray([]);
     self.weeknumber = ko.observable();
     self.username = ko.observable();
     self.complete = ko.observable();

      // FILTER MODEL ITEMS
      //var MODEL_COLS = ["username", "weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "pick" ];
      var MODEL_COLS = ["username", "weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "pick"];

      self.showGameDate = function(gamedate)
      {
         var dayofweek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][new Date(Date.parse(gamedate)).getDay()];
         return gamedate + " " + dayofweek;
      };

      // Model Construction
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("WeekPickViewModel : parse pickweek from server");
        cflog(data);
        self.games(data.games);
        self.games( self.games().sort(function(l, r) { return l.timeinmillis == r.timeinmillis ? 0 : (l.timeinmillis < r.timeinmillis ? -1 : 1) }));
        self.weeknumber(data.weeknumber);
        self.username(data.username);
        self.complete(data.complete);
        refreshPickViewModel();  
      };

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 
          CFBAPI.get('/player/pickweek/' + weeknumber, 
            function (result) {self.parseWeekFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load Week");
                cflog(textStatus);
                cflog(errorThrown);
            });

        return true;
      };

      // SAVE
      //
      self.saveWeek = function() {
          var jsonData = self.cleanJSON();

          cflog(jsonData);

          CFBAPI.post('/player/pickweek/picks/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Your picks Were saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save picks");
                cflog(textStatus);
                cflog(errorThrown);
                      });


            return true;
      };

      // Behaviours   
      // Set hash to trigger routes - weeks scores or make picks
      //
      self.goToPlayerPickWeeksList = function() { 
          cflog('goToPlayerPickWeeksList : ');
          location.hash = '/playerweeks'; 
      };


      // INIT 
      //
      cflog("WeekPickViewModel : init : " + weeknumber);
      self.loadWeek(weeknumber);
  };

  // ***************************************************************************************************************************************************** //

  // ******************************************************************************************************************
  // Player Home 
  //
  // Show current scores grid
  //
  function PlayerHomeViewModel() 
  {
      cflog("PlayerHomeViewModel : init : ");
      var self = this;  
      self.columnnames = ko.observableArray([]);
      self.rows = ko.observableArray([]);
      self.totals = ko.observableArray([]);
      self.averages = ko.observableArray([]);

      // Model Construction
      // take api results and build model
      self.loadLeaderboardFromServer = function(data){
        cflog(data);
        self.columnnames(data.columnNames);
        self.rows(data.rows);
        self.totals(data.totals);
        self.averages(data.averages);
      };

      self.loadLeaderBoard = function() {
        cflog("PlayerHomeViewModel : load leaderboard : ");
        CFBAPI.get('/player/leaderboard', 
            function (result) {
                self.loadLeaderboardFromServer(result); 
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load leaderboard");
                cflog(textStatus);
                cflog(errorThrown);
            });
        return true;
      };

      //INIT
      //
      self.loadLeaderBoard();
  };


  // ******************************************************************************************************************
  // ScoreboardViewModel 
  //
  // Show current scores grid
  //
  function ScoreboardViewModel(weeknumber) 
  {
      cflog("ScoreboardViewModel : init : ");
      var self = this;  
      self.columnnames = ko.observableArray([]);
      self.rows = ko.observableArray([]);
      self.totals = ko.observableArray([]);


      self.dateTimeField = function ( game ) {
        return gametime = game.gamedate + " " + game.time.label
      }

      self.booleanConversion = function ( value ) {
        return value.toString();
      }

      self.loadScores = function(weeknumber) {
        cflog("ScoreboardViewModel : loadScores : " + weeknumber);
        CFBAPI.get('/player/scoreboard/' + weeknumber, 
            function (result) {
                self.loadScoresFromServer(result); 
                refreshScoreBoardVewModel(); 
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load scoreboard");
                cflog(textStatus);
                cflog(errorThrown);
            });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadScoresFromServer = function(data){
        self.columnnames(data.columnNames);
        self.rows(data.rows);
        self.totals(data.totals);
      };

      //INIT
      //
      self.loadScores(weeknumber);
  };


  function refreshScoreBoardVewModel()
  {
      // for each row: 
      // - find winner and mark it
      // - find home team and mark it
      // - find players pick and mark it
      $('tbody > tr').each( function(){
        var winner   = $(this).find('#winner');
        var favorite = $(this).find('#favorite');
        var underdog = $(this).find('#underdog');
        var favoredlocation = $(this).find('#favoredlocation');
        var completed = $(this).find('#completed');
        var columns = $(this).find('td.userpick');

        // green up the winner
        //
        if( winner.val() == favorite.text() ) 
        {
          $(favorite).addClass("green");
        } else if ( winner.val() == underdog.text() )
        {
          $(underdog).addClass("green");
        }

        //  bold up home team
        //
        if( favoredlocation.val() == "HOME" ) 
        {
          $(favorite).addClass("bold");
        } else if ( favoredlocation.val() == "AWAY" )
        {
          $(underdog).addClass("bold");
        }

        // TODO - green / red up picks that matched
        //
        $(columns).each( function(){
          if( winner.val() == $(this).text() ) 
          {
            $(this).addClass("green");
          } else if ( completed.val() == "true" ) {
            $(this).addClass("red");
          }
        });
      });
  }

  // ******************************************************************************************************************
  // Player Weeks Model 
  //
  // handles list of weeks, results are shown if applicable, edit, delete controls presented
  //
  function PlayerWeeksViewModel() 
  {
      cflog("PlayerWeeksViewModel : init : ");

      var self = this;   
      self.weeks = ko.observableArray([]);
      
      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      };

      self.loadWeeks = function() {
        cflog("PlayerWeeksViewModel : loadWeeks ");
        CFBAPI.get('/player/weeks', 
            function (result) {self.loadWeeksFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load list of Weeks");
                cflog(textStatus);
                cflog(errorThrown);
        });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadWeeksFromServer = function(data){
        cflog("loadweeksfromserver");
        cflog(data);
        self.weeks(data);
        self.weeks( self.weeks().sort(function(l, r) {return l.weeknumber == r.weeknumber ? 0 : (l.weeknumber < r.weeknumber ? -1 : 1) }));
      };

      // Behaviours   
      // Set hash to trigger routes - weeks scores or make picks
      //
      self.goToPlayerPicks = function(week) { 
          cflog('goToPlayerPicks : ' + week.weeknumber);
          var wknum = week.weeknumber;

          if(typeof week.weeknumber == 'undefined')
          {
            cflog('goToPlayerPicks - bad week number');
          } else {
             location.hash = '/playerpicks/' + wknum; 
          }
      };

      self.goToWeekScore = function(week) {
          cflog('goToWeekScore : scoreboard');
          location.hash = '/scoreboard/' + week.weeknumber; 
      };

      // INIT
      // 

      self.loadWeeks();

  };

  // ******************************************************************************************************************
  // SCORE WEEK 
  // Admin Screen for entering scores for the games of a week
  //

  //
  // refeshGamesScoreViewModel
  function refeshGamesScoreViewModel()
  {
      // Radio Button - Hidden Input - Toggle
      // check our toggle buttons and hidden fields are synched up
      $('.datarow').each( function(){
          var winner   = $(this).find('.winner');
          
          if(typeof winner != "undefined" && winner.val() !== "")
          {
            $(".favorite, .underdog").each( function(){
              var team = $(this);
              if(team.text() == winner.val())
              {
                team.addClass("green");
                return false;
              }
            });
          }
        });

        /**********
           Spread Calc 
         As input is typed in: 
          check the values against the spread and apply green to winner
          update hidden field with value of team name

         **********/
        $("form").delegate(".row .input", "keyup", function() 
        {
          var clicked = $(this);
          var sibling = clicked.siblings('.input');   // class of input, not html of input
          var uscore;
          var fscore;
          var favwasclicked = true;

          if("sfav" == clicked.attr("name") ) 
          {
            fscore = parseInt(clicked.val());
            uscore = parseInt(sibling.val());
            favwasclicked = true;
          } else if ("sund" == clicked.attr("name") ) 
          {
            uscore = parseInt(clicked.val());
            fscore = parseInt(sibling.val());
            favwasclicked = false;
          }

          if(!isNaN(fscore) && !isNaN(uscore))
          {
            var spread = $(clicked).closest(".row").find(".spread").text();

            if(!isNaN(spread))
            {
              var diff = fscore-uscore;
              var favorite = clicked.closest(".row").find(".favorite");
              var underdog = clicked.closest(".row").find(".underdog");
              var winner   = clicked.siblings('.winner');

              if(diff >= spread)
              {
                $(favorite).addClass("green");
                $(underdog).removeClass("green");
                winner.val($(favorite).text()).change();
              } else {
                $(underdog).addClass("green");
                $(favorite).removeClass("green");
                winner.val($(underdog).text()).change();
              }
            }
          }
        });
  };

  function GamesScoreViewModel(weeknumber) 
  {
      var self = this;   
      self.weeknumber = ko.observable();
      self.games = ko.observableArray([]);
      self.published = ko.observable();
      

      // FILTER MODEL ITEMS
      var MODEL_COLS = ["weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "gamedate", "time", "label", "value", "scorefavored", "scoreunderdog", "winner", "completed", "published" ];

      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      }

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      // SAVE WEEK GAME SCORES
      //
      self.saveGameScores = function() {
          cflog(ko.toJSON(self));
          var jsonData = self.cleanJSON();
          cflog(jsonData);

          CFBAPI.post('/admin/week/score/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Week Scores Saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save Week Scores !");
                cflog(textStatus);
                cflog(errorThrown);
            });
          
        return true;
      };

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 
          CFBAPI.get('/admin/week/' + weeknumber, 
            function (result) {self.parseWeekFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load Week");
                cflog(textStatus);
                cflog(errorThrown);
            });

        return true;
      };

      // CANCEL
      //
      self.cancel = function() {
          cflog('GamesScoreViewModel : cancel');
          location.hash = '/weeks'; 
      };

      // Model Constructio
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("parseweekfromserver");
        cflog(data);
        self.games(data.games);
        self.weeknumber(data.weeknumber);
        self.published(data.published);
        refeshGamesScoreViewModel();  
      };

      // INIT 
      //
      self.loadWeek(weeknumber);
  }


</script>
<script>

<!--
/**
                              UTILS
 **************************************************************************************************************************************************************************
 ******************************************************************************************************************************************************************************/
-->

  var logtoconsole = true;

  var CFBUSER = (function () 
  {
    var user = {};
    
    user.isloggedin = function() {
      if(user.apikey)
      {
        return true;
      }

      return false;
    };

    user.isadmin = function() {
      
      if(user.role === 'ROLE_ADMIN')
      {
        return true;
      }

      return false;
    };

    user.init = function (data) {
        user.apikey = data.apikey;
        user.role = data.role;
        user.username = data.username;


        cflog("user init : " + user.apikey + ":" + user.role + ":" + user.username + ":");
    };
    
    user.logout = function(){
        user.apikey = '';
        user.role = '';
        user.username = '';
      };

    return user;
  }());

  //
  //LOGGING
  //
  // use a less common namespace than just 'log'
  function cflog(msg)
  {
      // attempt to send a message to the console
      try
      {
          if(logtoconsole) { console.log(msg) };
      }
      // fail gracefully if it does not exist
      catch(e){}
  }

 // Alert Block and Messaging
 //
 var CFBMESSAGE = (function () 
 {
     var mess = {};

     mess.error = function (message) {
        showmessage("alert-error", message);
     };

     mess.info = function (message) {
        showmessage("alert-info", message);
     };

     mess.success = function (message) {
        showmessage("alert-success", message);
     };

     mess.warn = function (message) {
        showmessage("alert-warn", message);
     };

     mess.clear = function () {
        cflog("CFBMESSAGE : clear");
        hidemessage();
     }

     function hidemessage() {
          $("#messagediv").html(null);
     }

     function showmessage(alertclass, message) {
          var data = { alertclass: alertclass, alertmessage: message};
          var messagesource = $("#message").html();
          var messagetemplate = Handlebars.compile(messagesource);
          $("#messagediv").html(messagetemplate(data));
     };

     return mess;
 }());

 // API for contacting Server
 //
 var CFBAPI = (function () 
 {
    var api = {};

    api.get = function (path, successhandler, errorhandler) {

        $.ajax({
          type: "GET",
          url: path+"?apikey="+CFBUSER.apikey,
          contentType: "application/json; charset=utf-8",
          success: successhandler,
          error: errorhandler
        });
       return true;
    };

    api.post = function(path, datapackage, successhandler, errorhandler) {
        $.ajax({
            type: "POST",
            url: path+"?apikey="+CFBUSER.apikey,
            data: datapackage,
            contentType: "application/json; charset=utf-8",
            success: successhandler,
            error: errorhandler
        });
        return true;
    };

    return api;
  }());

 // ADMINHELPER - referenced by sub nav tabs on admin screens
 // navigation items used in more than one screen, so lets pull out and put in one place
 // each of the Admin modesl can just use these
 //
 var ADMINNAVHELPER = (function () 
 {
    var nav = {};

    nav.goToUsersList = function () 
              {    
                cflog('goToUsersList');
                location.hash = '/users'; 
              };

    nav.goToWeeksList = function () 
            {    
              cflog('goToWeeksList');
              location.hash = '/weeks' 
            };

    nav.goToControls = function () 
            {    
              cflog('goToControls');
              location.hash = '/controls' 
            };
 
    return nav;
  }());


var CONSTANTS = (function ()
{
  var consts = {};

  // seriousle, move this to the server and make a call for it already
  //
  consts.times = [{ label: "12:00", value: "12:00" },{ label: "12:15", value: "12:15" },{ label: "12:30", value: "12:30" },{ label: "12:45", value: "12:45" },{ label: "1:00", value: "13:00" },{ label: "1:15", value: "13:15" },{ label: "1:30", value: "13:30" },{ label: "1:45", value: "13:45" },{ label: "2:00", value: "14:00" },{ label: "2:15", value: "14:15" },{ label: "2:30", value: "14:30" },{ label: "2:45", value: "14:45" },{ label: "3:00", value: "15:00" },{ label: "3:15", value: "15:15" },{ label: "3:30", value: "15:30" },{ label: "3:45", value: "15:45" },{ label: "4:00", value: "16:00" },{ label: "4:15", value: "16:15" },{ label: "4:30", value: "16:30" },{ label: "4:45", value: "16:45" },{ label: "5:00", value: "17:00" },{ label: "5:15", value: "17:15" },{ label: "5:30", value: "17:30" },{ label: "5:45", value: "17:45" },{ label: "6:00", value: "18:00" },{ label: "6:15", value: "18:15" },{ label: "6:30", value: "18:30" },{ label: "6:45", value: "18:45" },{ label: "7:00", value: "19:00" },{ label: "7:15", value: "19:15" },{ label: "7:30", value: "19:30" },{ label: "7:45", value: "19:45" },{ label: "8:00", value: "20:00" },{ label: "8:15", value: "20:15" },{ label: "8:30", value: "20:30" },{ label: "8:45", value: "20:45" },{ label: "9:00", value: "21:00" },{ label: "9:15", value: "21:15" },{ label: "9:30", value: "21:30" },{ label: "9:45", value: "21:45" },{ label: "10:00", value: "22:00" },{ label: "10:15", value: "22:15" },{ label: "10:30", value: "22:30" },{ label: "10:45", value: "22:45" },{ label: "11:00", value: "23:00" },{ label: "11:15", value: "23:15" },{ label: "11:30", value: "23:30" },{ label: "11:45", value: "23:45" }];

    return consts;
}());


</script>

<!--
/**********************************************************************************************************************************
 * Datepicker - Setup Plugin
 *
 **********************************************************************************************************************************/
-->
<script>
    /* Update datepicker plugin so that MM/DD/YYYY format is used. */

    $.extend($.fn.datepicker.defaults, 
    {
      parse: function (string) {
        var matches;
        if ((matches = string.match(/^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/))) {
          return new Date(matches[3], matches[1] - 1, matches[2]);
        } else {
          return null;
        }
      },
      format: function (date) {
        var
          month = (date.getMonth() + 1).toString(),
          dom = date.getDate().toString();
        if (month.length === 1) {
          month = "0" + month;
        }
        if (dom.length === 1) {
          dom = "0" + dom;
        }
        return month + "/" + dom + "/" + date.getFullYear();
      }
    });  
</script>


<script>
<!--
/**
                              ROUTES - SAMMY
 **************************************************************************************************************************************************************************
 ******************************************************************************************************************************************************************************/
-->

$.sammy(function() {

    var checkForAuthenticated = function(callback) 
    {  

       //TODO - skip if route is login submit
       //

       //TODO - check to see if apikey / user object in place
       //
       cflog("checkForAuthenticated : " + CFBUSER.isloggedin() + ":" + CFBUSER.apikey);
       cflog("checkForAuthenticated : " + (this.path != "#/login") + ":" + (this.path != "/view/index.html"));

       cflog(this)

       if( this.path != "#/login" && this.path != "/view/index.html" && this.path != "#/login-form" && !CFBUSER.isloggedin() )
       {
          cflog("not authenticated! going to login")
          //this.app.runRoute('get', '#/login');
          this.redirect('#/login');
       }  else {
          $.cookie("cfbconlin_apikey", CFBUSER.apikey, { expires : 10 });
          $.cookie("cfbconlin_username", CFBUSER.username, { expires : 10 });
          $.cookie("cfbconlin_role", CFBUSER.role, { expires : 10 });
          callback();
       }
    };

    var checkForAuthorized = function(callback) 
    { 

      // TODO 
      // if admin path and not admin, go back to home page?
      //

      // 

      cflog("checkForAuthorized : " + CFBUSER.isadmin());
      callback();
    };

    this.around(checkForAuthenticated).around(checkForAuthorized);

    //
    // handleNavigation
    // helper to perform navigation template calls
    // Can we keep navtemplate and subnavtemplate compiled vars somewhere? Safe us the hassle?
    //
    function handleNavigation(data)
    {
        CFBMESSAGE.clear();
        
        cflog("inside top navigation : " + CFBUSER.isadmin());

        var navsource = $("#top-navigation").html();
        var subnavsource = $("#sub-navigation").html();
        var navtemplate = Handlebars.compile(navsource);
        var subnavtemplate = Handlebars.compile(subnavsource);
        $("#navigationdiv").html(navtemplate(data));
        $("#subnavigationdiv").html(subnavtemplate(data));
    }

    //
    // Sign Out
    //
    this.get('#/signout', function()
    {
        cflog('Signout route');
        CFBUSER.logout();
        $.cookie("cfbconlin_apikey", null);
        var logout = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/view/index.html";  
        window.location.replace(logout);
    });

    //
    // Home Screen
    //
    this.get('#/home', function() 
    {
        cflog('Home Get route');
        //GLOBAL PAGE SETTINGS
        var data = { };

        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { disablenav: false, disablesubnav: true, home: true });             //top nav    
        $.extend(data, { title: "The Conlin Pool" } );                          //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#home").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new PlayerHomeViewModel());
    });

    //
    // Login Screen
    //
    this.get('#/login', function() 
    {
        cflog('Login Get route');
        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { disablenav: true, disablesubnav: true });             //top nav
        $.extend(data, { title: "" } );                                     //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#login").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        var remember = $.cookie('cfbconlin_remember');
        if ( remember == 'true' ) 
        {
          var username = $.cookie('cfbconlin_username');
          var password = $.cookie('cfbconlin_password');

          // autofill the fields
          $('#username').attr("value", username);
          $('#password').attr("value", password);
          $('#remember').prop("checked", true);
        }
    });

    //
    // Login Form Submit
    //
    this.post('#/login-form', function(context) 
    {
        cflog('Login Post route');
        var postdata = {};
        postdata.username = context.params.username;
        postdata.password = context.params.password;

        if ("on" == context.params.remember) 
        {          
          var username = context.params.username;
          var password = context.params.password;

          // set cookies to expire in 14 days
          $.cookie('cfbconlin_username', username, { expires: 180 });
          $.cookie('cfbconlin_password', password, { expires: 180 });
          $.cookie('cfbconlin_remember', true, { expires: 180 });
        } else {
        // reset cookies
          $.cookie('cfbconlin_username', null);
          $.cookie('cfbconlin_password', null);
          $.cookie('cfbconlin_remember', null);
        }

        cflog(postdata);
        var serializedData = $(postdata).serialize(); 

        cflog(serializedData);
        cflog(JSON.stringify(postdata));
        //post submit login form
        //

        var request = $.ajax({
          url: "/apikey/login",
          type: "post",
          dataType: "json",
          contentType: "application/json",
          data: JSON.stringify(postdata),
          success: function(req){
                  cflog("success");
                  cflog(req);
                  CFBUSER.init(req);
                  if(CFBUSER.isadmin())
                  {
                    location.hash = '/home';
                  } else {
                    location.hash = '/home';
                  }
              },
          error:function(req){
                 cflog("failure");
                 CFBMESSAGE.error("Could not login, is your password and username correct?");
                 cflog(req);
             }          
        });
        return false;
    });


    //
    // Control Screen (Admin)
    //
    this.get('#/controls', function() 
    {
        cflog('Controls Get route');
        //GLOBAL PAGE SETTINGS
        var data = { };

        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: true});    //top nav
        $.extend(data, { controls: true,  title: "Admin - Controls" } );            //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#controls").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new ControlViewModel());
    });

    //
    // Create / Edit User
    //
    this.get('#/user/:userid', function() 
    {
        
        if(typeof this.params.userid == "undefined" || this.params.userid == "undefined")
        {
           cflog('user route : ADD : ');
        } else {
           cflog('user route : EDIT : ' + this.params.userid);
        }

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});  
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {users: true, title: "Admin - Create / Edit User" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#user-edit").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new UserViewModel( this.params.userid ) );
    });

    //
    // List Users
    //
    this.get('#/users', function() 
    {
        cflog('users route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: true});    //top nav
        $.extend(data, { users: true, title: "Admin - List All Users" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#users-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new UsersViewModel());       
    });

    //
    // List Weeks
    //
    this.get('#/weeks', function() 
    {
        cflog('weeks route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: true});                                       //top nav
        $.extend(data, {weeks: true, title: "Admin - List All Weeks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#weeks-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new WeeksViewModel());
    });


    //
    // Scoreboard
    //
    this.get('#/scoreboard/:weeknumber', function() 
    {
        cflog('scoreboard weeknumber : ' + this.params.weeknumber);

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: false, makeYourPicks: true,});                                       
        $.extend(data, {disablesubnav: true,  title: "Scoreboard - Week - " + this.params.weeknumber });      
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#scoreboard").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new ScoreboardViewModel(this.params.weeknumber));
    });

    //
    // User List Weeks
    //
    this.get('#/playerweeks', function() 
    {
        cflog('playerweeks route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: false, makeYourPicks: true,});                                       //top nav
        $.extend(data, {disablesubnav: true,  title: "Player - List All Weeks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#player-weeks-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new PlayerWeeksViewModel());
    });

    //
    // Player Picks Week - player-picks
    // For a week - a player can select winners
    //
    this.get('#/playerpicks/:weeknumber', function() 
    {
        cflog('playerpicks weeknumber : ' + this.params.weeknumber);

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: false, makeYourPicks: true,});                           //top nav
        $.extend(data, {disablesubnav: true,  title: "Player - Make Your Picks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#player-picks").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new WeekPickViewModel(this.params.weeknumber));
    });

    //
    // Create / Edit Week
    //
    this.get('#/week/:weeknumber', function() 
    {
        
        if(typeof this.params.weeknumber == "undefined" || this.params.weeknumber == "undefined")
        {
           cflog('week route : ADD : ');
        } else {
          cflog('week route : EDIT : ' + this.params.weeknumber);
        }

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {weeks: true, title: "Admin - Create / Edit Week" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#week-edit").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new GamesViewModel(this.params.weeknumber));
    });

    //
    // Score Week
    //
    this.get('#/week/score/:weeknumber', function() 
    {

        if(typeof this.params.weeknumber == "undefined" || this.params.weeknumber == "undefined")
        {
           cflog('week score route : ADD : ');
           this.params.weeknumber = -1;
        } else {
           cflog('week score route : EDIT : ' + this.params.weeknumber);
           
           //TODO - call server for week data
           //
           // does it go here? or simply in the init of the view model ?
        }

        //GLOBAL PAGE SETTINGS
        var data = { debug: true };

        //NAVIGATION
        $.extend(data, { isadmin: CFBUSER.isadmin()});
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {weeks: true, title: "Admin - Score Week" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#week-score").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new GamesScoreViewModel(this.params.weeknumber));
    });

    function onloginpageload()
    {
      $('#loginbutton').on('click', function (e) {
           loginPreSubmitProcessor();
      })


    }

    //
    // Init:
    //
    this.get('', function() {
        this.app.runRoute('get', '#/login');
    });

    // check for cookie and re-init user with key value
    //

    CFBUSER.apikey = $.cookie("cfbconlin_apikey");
    CFBUSER.username = $.cookie("cfbconlin_username");
    CFBUSER.role = $.cookie("cfbconlin_role");

}).run();  

</script>

<!--
/**********************************************************************************************************************************
 * Login & Carousel
 *
 **********************************************************************************************************************************/
-->

<script>

  // get that carousel fired up and rotating
  !function ($) {
    $(function(){
      // carousel demo
      $('#myCarousel').carousel()
    })
  }(window.jQuery);

  // keep your eyes peeled for enter key as submit
  function checkSubmit(e)
  {
     if(e && e.keyCode == 13)
     {
        loginPreSubmitProcessor();
     }
  }

</script>

</body>
</html>